<template>


    <el-button link @click="open">{{ buttonText }}</el-button>
    <el-button v-if="type == 'SHOW'" @click="historyVisible = true">历史文件</el-button>

    <el-dialog draggable class="dialog" width="400px" v-model="editVisible" :destroy-on-close="true">


        <el-upload ref="upload" class="upload-demo" v-model:file-list="fileList" drag action="#" :auto-upload="false"
            :on-exceed="handleExceed" :limit="1" multiple>
            <el-icon class="el-icon--upload">
                <upload-filled />

            </el-icon>
            <div class="el-upload__text">
                拖拽文件或者<em>点击上传</em>
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    上传新文件后，可在历史文件中查看旧文件
                </div>
            </template>
        </el-upload>

        <div class="download-template">
            <el-button @click="editVisible = false">取 消</el-button>
            <el-button :loading="submitLoading" type="primary" @click="submitUpload">确 定</el-button>
        </div>

    </el-dialog>


    <el-dialog draggable class="dialog" width="400px" v-model="historyVisible" :destroy-on-close="true">

        <el-timeline>
            <el-timeline-item v-for="(fileInfo, index) in filenameList" :key="index" :timestamp="(fileInfo as any).time">

                <el-button link @click="downloadFile(fileInfo)">{{ (fileInfo as any).name }}</el-button>
                
            </el-timeline-item>
        </el-timeline>

    </el-dialog>

</template>
    
<script setup lang='ts'>
import * as _ from 'lodash'
import { ElMessage, genFileId, UploadFiles, UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import { ComponentInternalInstance, getCurrentInstance, onMounted, PropType, ref, watch } from 'vue';

const proxy: any = (getCurrentInstance() as ComponentInternalInstance).proxy
const props = defineProps({

    //文件在内部存储是一个字符串数组 此处为数组
    dataList: {
        type: String,
        default: ""
    },

    // EDIT  编辑时候的模式，此时点击时有上传功能和查看历史文件功能
    // SHOW  展示模式，允许下载和查看历史文件功能
    type: {
        type: String as PropType<'EDIT' | 'SHOW'>,
        default: "EDIT"
    }
})

const buttonText = ref("上传文件" as String);

const editVisible = ref(false)

const fileList = ref([])

const filenameList = ref([] as Array<Object>)

onMounted(() => {
    console.log(props.dataList)

    if (!_.isEmpty(props.dataList) && props.dataList.length > 0) {
        filenameList.value = JSON.parse(props.dataList)
        buttonText.value = (filenameList.value[filenameList.value.length - 1] as any).name
    }
})
const upload = ref<UploadInstance>()

const open = async () => {

    if (props.type == "EDIT") {
        editVisible.value = true
    } else {
        let vo = {
            id: (filenameList.value[filenameList.value.length - 1] as any).id,
            name: buttonText.value
        }
        let reslutData = (await proxy.$api.metafile.downFile(vo)).data

        proxy.$api.metafile.downloadNeedName(reslutData.filename,buttonText.value)
        // proxy.$api.metafile.download(reslutData.filename)
    }
}


// 单文件时 新文件会替代旧文件
const handleExceed: UploadProps['onExceed'] = (files) => {

    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file);

}

const emits = defineEmits(['afterSubmit', 'update:dataList']);
const submitLoading = ref(false)

const submitUpload = _.debounce(async () => {

    submitLoading.value = true
    let tempFileList: UploadFiles = fileList.value
    var formData = new FormData();
    formData.append("file", tempFileList[0].raw as UploadRawFile)
    formData.append("filename", tempFileList[0].name)

    let response = (await proxy.$api.metafile.uploadMountFile(formData))

    if (response.code == 200) {
        let filename = response.data.mountFile
        filenameList.value.push(filename)
        let tempStr = JSON.stringify(filenameList.value);
        emits("update:dataList", tempStr)
        filenameList.value = JSON.parse(tempStr);
        buttonText.value = filename.name
    }

    ElMessage.success({ message: response.message })

    submitLoading.value = false
    editVisible.value = false
    emits("afterSubmit")

}, 300)


const historyVisible = ref(false)

const downloadFile = async (fileInfo:any) => {
    let vo = {
            id: fileInfo.id,
            name: fileInfo.name
        }
    let reslutData = (await proxy.$api.metafile.downFile(vo)).data

    proxy.$api.metafile.downloadNeedName(reslutData.filename,fileInfo.name)
    // proxy.$api.metafile.download(reslutData.filename)
}

watch(fileList, (val, oldVal) => {
    console.log(val,oldVal)
    console.log(`new: ${val}, old: ${oldVal}`)
},

)

//如果dataList更改，那么filenameList那随之修改
watch(props,(props) => {
    console.log("props",props);
    if (!_.isEmpty(props.dataList) && props.dataList.length > 0) {
        filenameList.value = JSON.parse(props.dataList)
        buttonText.value = (filenameList.value[filenameList.value.length - 1] as any).name
    }
})

</script>
    
<style>

</style>